package com.lin.java.tool.file.service.chain;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.lin.java.tool.file.dao.po.SysFileConfigEntity;
import com.lin.java.tool.file.model.FileRecord;
import com.lin.java.tool.general.enums.PlatformEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author: linjiang
 * @date: 2025/1/21
 */
@Slf4j
public class AlibabaFileChain extends AbstractFileChain {

    public AlibabaFileChain(FileChain delegate) {
        super(delegate, PlatformEnum.ALIBABA);
    }

    @Override
    protected FileRecord uploadOss(MultipartFile file, SysFileConfigEntity fileConfig) throws IOException {
        // 本地文件上传
        log.info("阿里云对象存储上传。。。。。。。。。。。。");
        String fileName = file.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(fileName);
        // 上传文件
        String fullPath = fullPath(suffix) + UUID.fastUUID().toString(true) + "." + suffix;

        OSS ossClient = createOssClient(fileConfig);
        try (InputStream inputStream = file.getInputStream()) {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(fileConfig.getBucket(), fullPath, inputStream);
            // 发送上传请求
            ossClient.putObject(putObjectRequest);
            return FileRecord.builder()
                    .platform(platform)
                    .bucket(fileConfig.getBucket())
                    .path(fullPath)
                    .originFileName(fileName)
                    .suffix(suffix)
                    .size(file.getSize())
                    .build();
        } catch (OSSException oe) {
            log.error("上传文件到阿里云oss异常:[{}]", oe.getErrorCode(), oe);
        } catch (ClientException ce) {
            log.error("阿里云对象连接网络异常:[{}]", ce.getMessage(), ce);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    @Override
    protected InputStream downloadOss(FileRecord fileReord, SysFileConfigEntity config) throws IOException {
        OSS ossClient = createOssClient(config);
        try {
            // 下载
            GetObjectRequest request = new GetObjectRequest(fileReord.getBucket(), fileReord.getPath());
            request.setRange(0, fileReord.getSize());
            OSSObject object = ossClient.getObject(request);
            InputStream stream = object.getObjectContent();
            return new ByteArrayInputStream(IoUtil.readBytes(stream));
        } catch (OSSException oe) {
            log.error("阿里云对象下载异常:[{}]", oe.getErrorMessage(), oe);
        } catch (ClientException ce) {
            log.error("阿里云对象连接网络异常:[{}]", ce.getErrorMessage(), ce);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    /**
     * 创建OSSClient实例。
     *
     * @param fileConfig
     * @return
     */
    private static OSS createOssClient(SysFileConfigEntity fileConfig) {
        return new OSSClientBuilder().build(fileConfig.getOssUrl(), fileConfig.getOssAccessKeyId(), fileConfig.getOssAccessKeySecret());
    }
}
